﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Acme.BookStore.Authors;
using Acme.BookStore.Books;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Form;
using Volo.Abp.Features;

namespace Acme.BookStore.Web.Pages.Books
{
    [RequiresFeature("BookStore.Books")]
    [Authorize(Permissions.BookStorePermissions.Books.Create)]
    public class CreateModalModel : BookStorePageModel
    {
        [BindProperty]
        public CreateBookViewModel Book { get; set; }

        public List<SelectListItem> Authors {get;set;}

        private readonly IBookAppService _bookAppService;

        public CreateModalModel(IBookAppService bookAppService)
        {
            _bookAppService = bookAppService;
        }

        public async void OnGet()
        {
            Book = new CreateBookViewModel();

            Authors = (await _bookAppService.GetAuthorLookupAsync())
                .Items.Select(r => new SelectListItem(r.Name, r.Id.ToString()))
                .ToList();
        }

        public async Task<IActionResult> OnPostAsync()
        {
            var createUpdateBook = ObjectMapper.Map<CreateBookViewModel, CreateUpdateBookDto>(Book);
            await _bookAppService.CreateAsync(createUpdateBook);
            return NoContent();
        }

        public class CreateBookViewModel
        {
            [Required]
            [StringLength(BookConsts.MaxNameLength)]
            public string Name { get; set; }

            [Required]
            public BookType Type { get; set; } = BookType.Undefined;

            [Required]
            [DataType(DataType.Date)]
            public DateTime PublishDate { get; set; } = DateTime.Now;

            [Required]
            public float Price { get; set; }

            [SelectItems(nameof(Authors))]
            [DisplayName("Author")]
            [Required]
            public Guid AuthorId { get; set; }
        }
    }
}